<template>
    <div class="panel full-panel flex-column _chat_panel">
        <div class="flex-full _list_bg">
            <Message v-for="(messge, i) in data.messages" :status="data.status[i]" :message="messge"></Message>
        </div>
        <div class="message_sender_box">
            <div class="_message_tools">
                <cb-button no-hover-color class="item">
                    <i class="bi bi-gear"></i>
                </cb-button>
            </div>
            <div class="flex-column _message_sender">
                <div class="_tools"></div>
                <textarea contenteditable="true" @focus="addEnterEvent" @blur="remEnterEvent" spellcheck="false" class="full-panel _message_input" v-model="data.sender"></textarea>
            </div>
        </div>
    </div>
</template>
<script setup>
import { randomId } from '@/frontend/utils/utils';
import { reactive, onActivated, onMounted } from 'vue';
import {gptTextTrans} from '@frontend/utils/utils'
import Message from './message.vue'
import $ from 'jquery'
import { useLayoutStore } from '@frontend/stores/pinia/layoutStore'
const layouts = useLayoutStore()

window.exchanger = window.exchanger || new window.Exchanger()

const STATUS = {
    RUNNING: 'running',
    WHATING: 'waiting',
    DONE: 'done'
}
onActivated(()=>{
    console.log('activate chat', )
})
const data = reactive({
    code: randomId(), //route?.query?.code,
    sender: '',
    messages: [],
    curIndex: -1,
    status: []
})

onMounted(()=>{
    const active = layouts.getActiveTabVo
    active.id && window.exchanger
        .putInvoke('get-chat-message-list', active.id )
        .then( (subs) => { 
            data.messages = subs
        })
}) 

const recive = (ename, index, chatId)=>{
    const curIndex = index
    const fn = (sender, parsed)=>{
        const msg = data.messages[curIndex]
        // parsed.choices[0].delta.content
        if(parsed.error){
            msg.repeat += ` [${parsed.e?.message}]`
            data.status[curIndex] = STATUS.DONE
            window.exchanger.removeEvent(ename, fn)
            return
        }
        const d = parsed.choices[0].delta ? parsed.choices[0].delta : parsed.choices[0]// parsed.choices[0] && parsed.choices[0].text ? parsed.choices[0].text : (parsed.choices[0].delta?.content)
        let s = d && d.text ? d.text : (d?.content)
        console.log(s)
        s = gptTextTrans(s)
        msg.repeat += s
        if( parsed.choices[0]?.finish_reason === 'stop' ){
            data.status[curIndex] = STATUS.DONE
            window.exchanger.removeEvent(ename, fn)
        }
    }
    return fn
}
const fn = (e)=>{
    const txtare = e.target
    $(txtare).on('keydown', async function(e){

        if(e.keyCode==13){
            if(!isCheck(data.sender)){
                return
            }
            const active = layouts.getActiveTabVo
            const tempEventName = "temp-event-" + Math.floor( Math.random(1,1000)*1000000);
            data.messages.push({
                prompt: data.sender,
                repeat: ''
            })
            data.curIndex = data.messages.length-1
            data.sender = data.sender.trim('\n')
            data.status[data.curIndex] = STATUS.RUNNING
            
            window.exchanger.onEvent(tempEventName, recive(tempEventName, data.curIndex, active.id))
            window.exchanger.put('chat-send-message', {
                chat_id: active.id,
                message: [
                    {"role": "user", "content": data.sender}
                ], 
                callbackEvent: tempEventName
            })
            data.sender = ''
            $(txtare).blur()
        }
    });
}
const addEnterEvent = fn
const remEnterEvent = (e)=>{
    const txtare = e.target
    $(txtare).off('keydown')
}

function isCheck(msg=''){
    return !!msg.replace(/\s+/g, '')
}

</script> 
<style lang="scss"> 
._chat_panel {
    overflow-y: auto;
    ._list_bg{
        overflow-y: auto;
    }
}
.message_sender_box{
    margin: 1rem;
    margin-top:0;
}
._message_sender{
    ._message_input{
        min-height:35px;
        max-height:35px;
        background-color: $bg-color;
        border-radius: 8px;
        outline: none;
        color: $ft-message-box-dark;
        padding:5px;
        transition-duration: 0.3s;
        border: 1px solid #3e3e3e;
        font-size:1.2rem;
        overflow-y: auto;
        &::-webkit-scrollbar {
            display: none;
        }
        &:focus{
            background-color: #fff;
            color: $ft-dart-color;
            border: 1px solid #045450;
            box-shadow: 0px 0px 3px #4ee1cc;
            min-height:80px;
            max-height:350px;
            &::-webkit-scrollbar {
                display:block;
            }
        }
    }
}
</style> 
